package com.fit.spring.boot.proxy.extension.interceptor;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.aopalliance.intercept.MethodInterceptor;

/**
 * 拦截器配置接口
 * 规范使用,避免每次调用方法,开发者每次都创建一个新的拦截器
 * @author hcl
 *
 */
public abstract class InterceptorConfigurationAware implements InterceptorConfiguration{

	/**
	 * 注册的拦截器
	 */
	private Map<String, MethodInterceptor> methodInterceptorsMap = new HashMap<String, MethodInterceptor>();
	
	
	{
		registeredInterceptors(methodInterceptorsMap);
	}
	
	/**
	 * 拦截器注册
	 * @return
	 */
	public abstract void registeredInterceptors(Map<String, MethodInterceptor> methodInterceptorsMap);
	
	
	
	/**
	 * 获取bean拦截器key
	 * @param beanClass
	 * @return
	 */
	public abstract String[] getBeanInterceptorsKeys(Config config);
	
	/**
	 * 获取bean方法拦截器key
	 * @param beanClass
	 * @param method
	 * @return
	 */
	public abstract String[] getBeanMethodInterceptorsKeys(Config config);
	
	
	@Override
	public void registeredBeanInterceptors(Config config) {
		String[] keys = getBeanInterceptorsKeys(config);
		if(keys == null || keys.length == 0){
			return ;
		}
		HashSet<String> keySet = new HashSet<String>(Arrays.asList(keys));
		keys = keySet.toArray(new String[keySet.size()]);
		for(String key : keys){
			MethodInterceptor interceptor = methodInterceptorsMap.get(key);
			if(interceptor == null){
				throw new RuntimeException("bean 拦截器配置异常！key '" + key + "' 没有找到拦截器。");
			}
			config.addMethodInterceptor(interceptor);
		}
	}

	@Override
	public void registeredBeanMethodInterceptors(Config config) {
		String[] keys = getBeanMethodInterceptorsKeys(config);
		if(keys == null || keys.length == 0){
			return ;
		}
		HashSet<String> keySet = new HashSet<String>(Arrays.asList(keys));
		keys = keySet.toArray(new String[keySet.size()]);
		for(String key : keys){
			MethodInterceptor interceptor = methodInterceptorsMap.get(key);
			if(interceptor == null){
				throw new RuntimeException("bean 拦截器配置异常！key '" + key + "' 没有找到拦截器。");
			}
			config.addMethodInterceptor(interceptor);
		}
	}
	
}
